/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved.
 */

package com.huawei.chengdu.meetingdemo.util;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import androidx.annotation.NonNull;

/**
 * 类名：GlobalHandler
 * 描述：消息转发handler
 */
public class GlobalHandler extends Handler {
    protected static final String TAG = "GlobalHandler";
    private static volatile GlobalHandler instance = null;

    private GlobalHandler(@NonNull Looper looper) {
        super(looper);
    }

    /**
     * 获取HandlerFactory的单例
     *
     * @return HandlerFactory的实例
     */
    public static GlobalHandler getInstance() {
        if (instance == null) {
            synchronized (GlobalHandler.class) {
                if (instance == null) {
                    instance = new GlobalHandler(Looper.getMainLooper());
                }
            }
        }

        return instance;
    }

    @Override
    public void handleMessage(Message msg) {
        LogUtil.debug(TAG + " handleMessage");
        Object object = msg.obj;
        if (object instanceof GlobalHandlerAdapter) {
            GlobalHandlerAdapter handlerAdapter = (GlobalHandlerAdapter) object;
            // 如果handlerAdapter.obj为null，在使用时进行判断
            try {
                handlerAdapter.dataObserver.viewDataChanged(handlerAdapter.indKey, handlerAdapter.obj);
                LogUtil.debug(TAG + " handlerAdapter.dataObserver.viewDataChanged indKey:" + handlerAdapter.indKey);
            } catch (NullPointerException e) {
                LogUtil.error(TAG + " Exception: catch an exception in default viewDataChanged, id: " + handlerAdapter.indKey);
            } finally {
                msg.obj = null;
            }
        }
    }
}
